package com.yf.smsprovider;

import java.util.ArrayList;

import org.xmlpull.v1.XmlSerializer;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.util.Xml;
import android.view.View;

public class MainActivity extends Activity {
	private ArrayList<Sms> smsList = new ArrayList<Sms>();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		Log.v("smsprovider.onCreate", String.valueOf(android.os.Build.VERSION.SDK_INT));
	}

	public void querySms(View v) {
		ContentResolver resolver = getContentResolver();
		// 通过查看SmsProvider源码发现子路径传null代表查询所有的短信
		Uri uri = Uri.parse("content://sms");
		String[] projection = { "address", "date", "body" };
		Cursor cursor = resolver.query(uri, projection, null, null, null);

		while (cursor.moveToNext()) {
			Sms sms = new Sms();
			sms.address = cursor.getString(0);
			sms.date = cursor.getString(1);
			sms.body = cursor.getString(2);
			smsList.add(sms);
			Log.v("smsprovider.querySms", sms.toString());
		}
	}

	public void backupSms(View v) {
		XmlSerializer serializer = Xml.newSerializer();
		try {
			serializer.setOutput(openFileOutput("sms.xml", MODE_PRIVATE), "utf-8");
			serializer.startDocument("utf-8", true);
			serializer.startTag(null, "smslist");

			for (Sms sms : smsList) {
				serializer.startTag(null, "sms");
				serializer.startTag(null, "address");
				serializer.text(sms.address);
				serializer.endTag(null, "address");

				serializer.startTag(null, "date");
				serializer.text(sms.date);
				serializer.endTag(null, "date");

				serializer.startTag(null, "body");
				serializer.text(sms.body);
				serializer.endTag(null, "body");

				serializer.endTag(null, "sms");
			}

			serializer.endTag(null, "smslist");
			serializer.endDocument();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void insertSms(View v) {
		ContentResolver resolver = getContentResolver();
		Uri url = Uri.parse("content://sms");
		ContentValues values = new ContentValues();
		values.put("address", "95533");
		values.put("type", "1");
		values.put("body", "国华先生：您的尾号为8888的金卡账户，工资入账18888.00元整，请注意账户资金变化。");
		values.put("date", System.currentTimeMillis());
		Uri rowId = resolver.insert(url, values);
		Log.v("smsprovider.insertSms", rowId.toString());
	}
}
